import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_questions/test_questions_logic.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'dart:math';

class PictureFlipWidget extends StatefulWidget {
  final TestQuestionsLogic logic;

  const PictureFlipWidget({
    Key? key,
    required this.logic,
  }) : super(key: key);

  @override
  State<PictureFlipWidget> createState() => _PictureFlipWidgetState();
}

class _PictureFlipWidgetState extends State<PictureFlipWidget>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  bool _showFrontSide = true;
  int? _selectedOptionId;

  // 添加网格项旋转动画控制器列表
  List<AnimationController> _rotationControllers = [];
  List<Animation<double>> _rotationAnimations = [];

  // 定义颜色列表
  final List<Color> colorList = [
    const Color(0xFFFB6F7A), // #FB6F7A
    const Color(0xFFFED441), // #FED441
    const Color(0xFF22C46F), // #22C46F
    const Color(0xFFC591FF), // #C591FF
  ];

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller);

    // 初始化已选择的答案
    final questionId = widget.logic.currentQuestion?.id;
    if (questionId != null &&
        widget.logic.userAnswers.containsKey(questionId)) {
      final answers = widget.logic.userAnswers[questionId];
      if (answers != null && answers.isNotEmpty) {
        _selectedOptionId = answers.first;
        // 如果已经选择了背面的选项，则显示背面
        if (_selectedOptionId != null &&
            widget.logic.currentQuestion?.options != null &&
            widget.logic.currentQuestion!.options!.length > 1) {
          // 检查选中的是哪个选项
          if (_selectedOptionId ==
              widget.logic.currentQuestion!.options![1].id) {
            // 如果选中的是第二个选项（背面），则显示背面
            _showFrontSide = false;
            _controller.value = 1.0;
          } else {
            // 如果选中的是第一个选项（正面），则显示正面
            _showFrontSide = true;
            _controller.value = 0.0;
          }
        }
      }
    }

    // 初始化网格项旋转动画控制器
    _initRotationControllers();
  }

  void _initRotationControllers() {
    final options = widget.logic.currentQuestion?.options ?? [];
    if (options.isEmpty) return;

    // 清除旧的控制器
    for (var controller in _rotationControllers) {
      controller.dispose();
    }
    _rotationControllers = [];
    _rotationAnimations = [];

    // 为每个选项创建动画控制器
    for (int i = 0; i < options.length; i++) {
      final controller = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: 800 + (i * 100)),
      );

      final animation = Tween<double>(begin: 0, end: 2 * pi).animate(
        CurvedAnimation(
          parent: controller,
          curve: Curves.easeInOut,
        ),
      );

      _rotationControllers.add(controller);
      _rotationAnimations.add(animation);

      // 添加动画状态监听，实现循环旋转
      controller.addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reset();
        }
      });

      // 延迟启动动画，错开时间
      Future.delayed(Duration(milliseconds: 200 * i), () {
        if (mounted) controller.forward();
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();

    // 释放所有旋转动画控制器
    for (var controller in _rotationControllers) {
      controller.dispose();
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final options = widget.logic.currentQuestion?.options ?? [];
    if (options.isEmpty) {
      return const Center(child: Text(''));
    }

    return GridView.builder(
      physics: const BouncingScrollPhysics(),
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      itemCount: options.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 24.w,
        crossAxisSpacing: 11.w,
        childAspectRatio: 158 / 100.0,
      ),
      itemBuilder: (context, index) {
        // 循环使用颜色列表
        final color = colorList[index % colorList.length];

        // final isSelected = _selectedOptionId == options[index].id;

        // 确保动画控制器列表长度足够
        if (index < _rotationAnimations.length) {
          return AnimatedBuilder(
            animation: _rotationAnimations[index],
            builder: (context, child) {
              return Transform(
                alignment: Alignment.center,
                transform: Matrix4.identity()
                  ..setEntry(3, 2, 0.001) // 添加透视效果
                  ..rotateY(_rotationAnimations[index].value),
                child: GestureDetector(
                  onTap: () {
                    clog('daskldjaslkd');
                    setState(() {
                      _selectedOptionId = options[index].id;
                      // 保存答案
                      if (widget.logic.currentQuestion != null) {
                        int questionId = widget.logic.currentQuestion!.id!;
                        widget.logic.userAnswers[questionId] = [
                          options[index].id!
                        ];
                      }

                      // 点击时触发旋转动画
                      if (!_rotationControllers[index].isAnimating) {
                        _rotationControllers[index].reset();
                        _rotationControllers[index].forward();
                      }
                    });
                  },
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    padding: EdgeInsets.all(8.w),
                    decoration: BoxDecoration(
                      color: color,
                      borderRadius: BorderRadius.circular(12.w),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 8.w,
                          offset: Offset(0, 4.w),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            margin: EdgeInsets.only(left: 4.w, top: 4.w),
                            child: Text(
                              optionLetter(index),
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 20.sp,
                                fontWeight: FontWeight.w700,
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Center(
                            child: ImageView(
                              imageUrl: options[index].image ?? '',
                              width: 80.w,
                              height: 80.w,
                            ),
                          ),
                        ),
                        20.horizontalSpace,
                      ],
                    ),
                  ),
                ),
              );
            },
          );
        }

        // 如果动画控制器未初始化，则显示默认视图
        return GestureDetector(
          onTap: () {
            clog('daskldjaslkd1');
            setState(() {
              _selectedOptionId = options[index].id;
              // 保存答案
              if (widget.logic.currentQuestion != null) {
                int questionId = widget.logic.currentQuestion!.id!;
                widget.logic.userAnswers[questionId] = [options[index].id!];
              }
            });
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(12.w),
            ),
            child: Row(
              children: [
                Align(
                  alignment: Alignment.centerLeft,
                  child: Container(
                    margin: EdgeInsets.only(left: 4.w, top: 4.w),
                    child: Text(
                      optionLetter(index),
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ),
                Expanded(
                    child: Center(
                  child: ImageView(
                    imageUrl: options[index].image ?? '',
                    width: 80.w,
                    height: 80.w,
                  ),
                )),
                20.horizontalSpace,
              ],
            ),
          ),
        );
      },
    );
  }

  String optionLetter(int id) {
    // 这里简化处理，实际应用中可能需要根据选项顺序来决定字母
    final letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
    final index = id % letters.length;
    return letters[index];
  }
}
